package com.xncoding.ThreadLocal;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.NotSerializableException;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class ThreadContext extends ConcurrentHashMap<String, Object> {

    protected static Class<? extends ThreadContext> contextClass = ThreadContext.class;
    protected static final ThreadLocal<? extends ThreadContext> threadLocal = new ThreadLocal<ThreadContext>() {
        protected ThreadContext initialValue() {
            try {
                return (ThreadContext)ThreadContext.contextClass.newInstance();
            } catch (Throwable var2) {
                throw new RuntimeException(var2);
            }
        }
    };

    public ThreadContext() {
    }

    public static ThreadContext getCurrentContext() {
        ThreadContext context = (ThreadContext)threadLocal.get();
        return context;
    }

    public void set(String key, Object value) {
        if (value != null) {
            this.put(key, value);
        } else {
            this.remove(key);
        }

    }

    public static void main(String[] args) {
        for (int i = 1; i <= 5; i++) {
            new Thread("Thread_" + i) {
                public void run() {
                    for (int j = 1; j <= 10; j++) {
                        ThreadContext ctx = ThreadContext.getCurrentContext();
                        ctx.set(getName()+"-"+j ,j);
                        System.out.println(getName()+"-"+j + ": count=" + ctx.get(getName()+"-"+j));
                    }
                };
            }.start();
        }
    }

}
